//
//  ToolBarView.m
//  Malena
//
//  Created by Dawn on 12-11-4.
//  Copyright (c) 2012年 Dawn. All rights reserved.
//

#import "ToolBarView.h"
#define TOOLBUTTONTAG 1000

@implementation ToolBarView
@synthesize delegate;
@dynamic isPlaying;

- (id)initWithFrame:(CGRect)frame iconArray:(NSArray *)toolIconArray
{
    self = [super initWithFrame:frame];
    if (self) {
        int count = toolIconArray.count;
        for (int i= 0;i < count;i++) {
            
            int x = frame.size.width - (count - i) * 45 -  2 * (count - i - 1);
            int y = 0;
            UIButton *toolBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [toolBtn setBackgroundImage:[UIImage imageNamed:[toolIconArray objectAtIndex:i]] forState:UIControlStateNormal];
            toolBtn.tag = TOOLBUTTONTAG + i;
            toolBtn.frame = CGRectMake(x, y, 45, 45);
            [toolBtn addTarget:self action:@selector(toolBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:toolBtn];
            
            toolBtn.alpha = 0.8;
            
            
        }
    }
    return self;
}

- (void) setIsPlaying:(BOOL)temp{
    isPlaying = temp;
    UIButton *button = (UIButton *)[self viewWithTag:TOOLBUTTONTAG + 2];
    if (!isPlaying) {
        [button setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    }else{
        [button setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    }
}

- (BOOL) isPlaying{
    return isPlaying;
}

#pragma mark -
#pragma mark ToolBarButtons
- (void) toolBarButtonClick:(id)sender{
    UIButton *button = (UIButton *)sender;
    if (button.tag == TOOLBUTTONTAG + 2) {
        self.isPlaying = !self.isPlaying;
    }
    if ([delegate respondsToSelector:@selector(didSelectedAtIndex:)]) {
        [delegate didSelectedAtIndex:button.tag - TOOLBUTTONTAG];
    }
}


- (void) layoutSubviews{
    int count = self.subviews.count;
    for (int i = 0; i < count; i++) {
        UIButton *button = (UIButton *)[self.subviews objectAtIndex:i];
        int x = self.frame.size.width - (count - i) * 45 -  2 * (count - i - 1);
        int y = 0;
        button.frame = CGRectMake(x, y, 45, 45);
    }
}

@end
